package com.example.port.service.impl;

import com.example.port.entity.StorageFee;
import com.example.port.mapper.StorageFeeMapper;
import com.example.port.service.StorageFeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class StorageFeeServiceImpl implements StorageFeeService {
    
    private final StorageFeeMapper storageFeeMapper;
    private final InvoiceServiceProxy invoiceServiceProxy;
    
    @Autowired
    public StorageFeeServiceImpl(StorageFeeMapper storageFeeMapper, InvoiceServiceProxy invoiceServiceProxy) {
        this.storageFeeMapper = storageFeeMapper;
        this.invoiceServiceProxy = invoiceServiceProxy;
    }
    
    @Override
    public int insertStorageFee(StorageFee fee) {
        // 检查是否已设置ID，如果没有，则自动生成ID
        if (fee.getFeeId() == null) {
            Long maxId = storageFeeMapper.getMaxFeeId();
            fee.setFeeId(maxId + 1);
        }
        return storageFeeMapper.insert(fee);
    }
    
    @Override
    public List<StorageFee> getAllStorageFees() {
        return storageFeeMapper.selectAll();
    }
    
    @Override
    public StorageFee getStorageFeeById(Long feeId) {
        return storageFeeMapper.selectById(feeId);
    }
    
    @Override
    @Transactional
    public int payStorageFee(Long feeId) {
        StorageFee fee = storageFeeMapper.selectById(feeId);
        if (fee == null) {
            return 0;
        }
        
        // 如果已支付，直接返回成功
        if ("已支付".equals(fee.getPaymentStatus()) || "已开票".equals(fee.getPaymentStatus())) {
            return 1;
        }
        
        fee.setPaymentStatus("已支付");
        int result = storageFeeMapper.update(fee);
        
        if (result > 0) {
            try {
                // 获取货物所属的客户ID
                Integer clientId = storageFeeMapper.getClientIdByCargoId(fee.getCargoId());
                if (clientId != null) {
                    // 创建包含一个费用ID的列表
                    List<Long> feeIds = new ArrayList<>();
                    feeIds.add(feeId);
                    
                    // 通过代理调用发票服务生成发票
                    invoiceServiceProxy.generateInvoiceFromStorageFees(feeIds, clientId);
                }
            } catch (Exception e) {
                // 记录错误但不影响支付流程
                System.err.println("生成发票时发生错误: " + e.getMessage());
                e.printStackTrace();
            }
        }
        
        return result;
    }
    
    @Override
    @Transactional
    public int deleteStorageFee(Long feeId) {
        // 先获取费用信息
        StorageFee fee = storageFeeMapper.selectById(feeId);
        if (fee == null) {
            System.out.println("未找到ID为" + feeId + "的仓储费用，无法删除");
            return 0;
        }
        
        System.out.println("准备删除仓储费用，ID:" + feeId + "，状态:" + fee.getPaymentStatus() + "，关联发票ID:" + fee.getInvoiceId());
        
        // 检查是否已支付且关联了发票
        if (("已支付".equals(fee.getPaymentStatus()) || "已开票".equals(fee.getPaymentStatus())) 
            && fee.getInvoiceId() != null) {
            
            // 获取关联的发票ID
            Long invoiceId = fee.getInvoiceId();
            System.out.println("仓储费用已支付且关联了发票，发票ID:" + invoiceId);
            
            try {
                // 直接删除关联的发票（一一对应关系）
                int result = invoiceServiceProxy.deleteInvoice(invoiceId);
                System.out.println("删除费用时同步删除了发票，发票ID: " + invoiceId + "，结果: " + (result > 0 ? "成功" : "失败"));
            } catch (Exception e) {
                // 记录错误但继续删除费用
                System.err.println("删除关联发票时发生错误: " + e.getMessage());
                e.printStackTrace();
            }
        } else {
            System.out.println("仓储费用未支付或未关联发票，不需要删除发票");
        }
        
        // 删除费用
        int result = storageFeeMapper.delete(feeId);
        System.out.println("删除仓储费用完成，ID:" + feeId + "，结果: " + (result > 0 ? "成功" : "失败"));
        return result;
    }
    
    @Override
    public int updateStorageFee(StorageFee fee) {
        if (fee == null || fee.getFeeId() == null) {
            return 0;
        }
        return storageFeeMapper.update(fee);
    }
} 
